<?
/**
 * @version 1.0
 * @uses lib.class.request
 * @uses lib.class.log
 */

class XMLException extends Exception {
	public function __construct($code, $message = '') {
		if (! is_int ( $code )) {
			throw new Exception ( 'Bad XMLException code:' . $code );
			return;
		}
		parent::__construct ( $message, $code );
	}
	
	public function __toString() {
		switch (Request::type ()) {
			case 'XML' :
				die ( $this->toXML () );
			case 'JSON' :
				die ( $this->toJSON () );
			default :
				die ( $this->toXML () );
		}
		
		die ( '' );
	}
	
	public function toXML() {
		header ( 'Content-type: text/xml' );
		$xml = simplexml_load_string ( '<exception>' . htmlspecialchars ( Log::get_session () ) . '</exception>' );
		$xml->code = $this->code;
		$xml->message = $this->message;
		$xml->file = $this->file;
		$xml->line = $this->line;
		
		$bk = $this->getTrace ();
		for($x = 0; $x < count ( $bk ); $x ++) {
			$xml->trace [$x] ['class'] = @$bk [$x] ['class'];
			$xml->trace [$x] ['function'] = $bk [$x] ['function'];
			$xml->trace [$x] ['line'] = @$bk [$x] ['line'];
			$xml->trace [$x] ['file'] = @$bk [$x] ['file'];
			$xml->trace [$x] ['object'] = @$bk [$x] ['object'];
			$xml->trace [$x] ['type'] = @$bk [$x] ['type'];
			@$xml->trace [$x] ['args'] = @$bk [$x] ['args'];
		}
		
		$code = $xml->asXML ();
		$code = explode ( "\n", $code );
		$code [0] = "<?xml version='1.0'?>\r\n<?xml-stylesheet type='text/xsl' href='/exception.xslt'?>";
		$code = implode ( "\n", $code );
		//$code = htmlspecialchars_decode($code, 0);
		return $code;
	}
	
	public function toJSON() {
		header ( 'Content-type: text/json' );
		$ret ['exception'] = Log::get_session ();
		$ret ['code'] = $this->code;
		$ret ['message'] = $this->message;
		$ret ['file'] = $this->file;
		$ret ['line'] = $this->line;
		
		$bk = $this->getTrace ();
		for($x = 0; $x < count ( $bk ); $x ++) {
			$ret ['trace'] [$x] ['class'] = @$bk [$x] ['class'];
			$ret ['trace'] [$x] ['function'] = $bk [$x] ['function'];
			$ret ['trace'] [$x] ['line'] = $bk [$x] ['line'];
			$ret ['trace'] [$x] ['file'] = $bk [$x] ['file'];
			$ret ['trace'] [$x] ['object'] = @$bk [$x] ['object'];
			$ret ['trace'] [$x] ['type'] = @$bk [$x] ['type'];
			$ret ['trace'] [$x] ['args'] = $bk [$x] ['args'];
		}
		
		$code = json_encode ( $ret );
		return $code;
	}
}

?>